/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package list;

/**
 *
 * @author ericzhou
 */
public class MyArrayList extends MyAbstractList {
    public static final int INITIAL_CAPACITY=10;
    private Object[] data=new Object[INITIAL_CAPACITY];
    
    public MyArrayList(){
        
    }
    
    public MyArrayList(Object[] os){
        this.data=os;
        size=os.length;
    }
    
    public void add(int index,Object o){
        ensureCapacity();
        for (int i=size-1;i>=index; i--){
            data[i+1]=data[i];
        }
        data[index]=o;
        size++;
    }
    
    private boolean ensureCapacity(){
        if (size>=data.length){
            Object[] newData=new Object[data.length*2];
            System.arraycopy(data, 0, newData, 0, data.length);
            data=newData;
            return false;
        }
        return true;
    }
    
    public void clear(){
        data= new Object[INITIAL_CAPACITY];
    }
    
    public boolean contains(Object o){
        for(int i=0; i<size;i++){
            if(o.equals(data[i])) return true;
        }
        return false;
    }
    
    public Object get(int index){
        return data[index];
    }
    
    public int indexOf(Object o){
        for (int i=0; i<size;i++){
            if(o.equals(data[i]))
                return i;
        }
        return -1;
    }
    
    public int lastIndexOf(Object o){
        for (int i=size-1; i>=0;i--){
            if(o.equals(data[i])) return i;
        }
        return -1;
    }
    
    public Object remove(int index){
        Object o=data[index];
        for (int i=index; i<size-1; i++){
            data[i]=data[i+1];
        }
        return o;
    }
    
    public Object set(int index, Object o){
        Object old=data[index];
        data[index]=o;
        return old;
    }
    
    public String toString(){
        StringBuffer result=new StringBuffer("[");
        
        for (int i=0; i<size; i++){
            result.append(data[i]);
            if(i<size-1) result.append(",");
        }
        
        return result.toString()+"]";
    }
    
}
